#region File Header
//----------------------------------------------------------------
// Copyright (C) 2002 Stefan Kyntchev
// All rights reserved.
//
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY 
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT 
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR 
// FITNESS FOR A PARTICULAR PURPOSE.
//----------------------------------------------------------------
#endregion File Header

namespace AirWeb.ApplicationTools.Diagnostics
{
	using System;
	using System.Configuration;
	using System.Diagnostics;
	using System.IO;
	using System.Text;
	using System.Threading;
	using System.Text.RegularExpressions;

	using AirWeb.Support;
	using AirWeb.ApplicationTools.Mail;

	/// <summary>
	/// This class implements a custom TraceListener that sends e-mails if the tracing text matches
	/// some pattern. A list of patterns, subjects and recipients is stored in the configuration
	/// 
	/// If, while tracing, the trace text matches the regular expression specified in "match"
	/// then an e-mail will be generated to the address specified in "email" with the subject
	/// specified in "subject" and body - the trace text 
	/// </summary>
	public class NotifiactionTraceListener : TraceListener
	{
		/// <summary>
		/// Implementation of base class method
		/// </summary>
		/// <param name="i_text"></param>
		public override void WriteLine(string i_text)
		{
			Write(i_text);
		}

		/// <summary>
		/// Implementation of base class method
		/// </summary>
		/// <param name="i_text"></param>
		public override void Write(string i_text)
		{
			TraceSender t  = new TraceSender(i_text);
			WaitCallback wcb = new WaitCallback(t.Send);
			ThreadPool.QueueUserWorkItem(wcb);
		}
	}

	/// <summary>
	/// If, while tracing, the trace text matches the regular expression specified in "match"
	/// then an e-mail will be generated to the address specified in "email" with the subject
	/// specified in "subject" and body - the trace text 
	/// </summary>
	class TraceSender
	{
		MailHelper m_helper = new MailHelper();
		string m_trace = null;

		/// <summary>
		/// Constructor
		/// </summary>
		/// <param name="i_trace">Thrace message to be checked</param>
		public TraceSender(string i_trace)
		{
			m_trace = i_trace;
		}

		/// <summary>
		/// Reads the configuration for notification handlers and if finds a match of the current trace
		/// e-mails to the handler's recipient
		/// </summary>
		/// <param name="i_text"></param>
		public void Send(object i_state)
		{
			foreach ( ApplicationConfiguration.NotificationHandler h in ApplicationConfiguration.NotificationHandlers)
			{
				Regex r = new Regex(h.Match); 
				Match m = r.Match(m_trace); 
				if(m.Success)
				{
					m_helper.SendMail(h.EMail,h.Subject,m_trace);
				}
			}
		}
	}
} 
